package com.api.controller;

import cn.hutool.core.util.StrUtil;
import com.api.entity.SysDept;
import com.api.entity.UserDept;
import com.api.log.Log;
import com.api.mapper.SysDeptMapper;
import com.api.utils.ParamsUtils;
import com.api.utils.Result;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

import static com.api.entity.table.SysDeptTableDef.SYS_DEPT;
import static com.api.entity.table.UserDeptTableDef.USER_DEPT;
import static com.api.entity.table.UserTableDef.USER;

/**
 * @Author: yangsf
 * @CreateDate: 2024/10/29
 */

@Slf4j
@RestController
@RequestMapping("/sysDept")
public class SysDeptController extends BaseController {


    @Autowired
    SysDeptMapper deptMapper;


    @Log("获取企业组织架构列表")
    @RequestMapping("/getList")
    public Result getList(@RequestParam Map<String,Object> params){
        QueryWrapper qw = QueryWrapper.create();
        qw.select(SYS_DEPT.ALL_COLUMNS).where(SYS_DEPT.STATUS.eq(1));
        if(params.containsKey("nameKeyword") && null != params.get("nameKeyword") && !StringUtils.isEmpty(params.get("nameKeyword"))){
            String nameKeyword = params.get("nameKeyword").toString();
            qw.and(SYS_DEPT.DEPT_NAME.like(nameKeyword));
        }
        qw.orderBy(SYS_DEPT.SORT_NUM,true);
        Page page = ParamsUtils.toPage(params);
        Page<SysDept> pages = deptMapper.paginate(page,qw);
        return Result.ok(pages);
    }

    @Log("获取企业组织架构")
    @RequestMapping("/getDepts")
    public Result getDepts(Integer kind){
        //kind: 0.全部树形结构 1.获取销售类部门
        if(null == kind){
            return Result.err("非法请求");
        }
        QueryWrapper qw = QueryWrapper.create();
        qw.select(SYS_DEPT.ALL_COLUMNS)
        .where(SYS_DEPT.PARENT_ID.eq(0))
        .and(SYS_DEPT.STATUS.eq(1))
        .orderBy(SYS_DEPT.SORT_NUM,true);
        List<SysDept> depts = deptMapper.selectListWithRelationsByQuery(qw);
        return Result.ok(depts);
    }


    @Log("获取企业组织架构")
    @RequestMapping("/checkName")
    public Result checkName(Long id, String deptName){
        if(StrUtil.isBlank(deptName)){
            return Result.err("部门名称必填");
        }
        SysDept dept = SysDept.create().select(SYS_DEPT.ALL_COLUMNS).where(SYS_DEPT.STATUS.eq(1)).and(SYS_DEPT.DEPT_NAME.eq(deptName)).one();
        if(null != dept){
            if(null == id || null != id && id.intValue() != dept.getId().intValue()){
                return Result.err("系统存在当前部门名称");
            }
        }
        return Result.ok();
    }

    @Log("获取部门下的员工")
    @RequestMapping("/getUserList")
    public Result getUserList(Long deptId){
        if(null == deptId){
            return Result.err("未获取到部门信息");
        }
        List<UserDept> list = UserDept.create()
                .select(USER_DEPT.ID, USER_DEPT.USER_ID, USER.USER_NAME.as("userName"))
                .leftJoin(USER).on(USER.ID.eq(USER_DEPT.USER_ID))
                .where(USER_DEPT.DEPT_ID.eq(deptId)).and(USER_DEPT.STATUS.eq(1))
                .list();
        return Result.ok(list);
    }

    @Log("移除部门下的员工")
    @RequestMapping("/removeUser")
    public Result removeUser(Long id){
        if(null == id){
            return Result.err("未获取到要删除的人员信息");
        }
        UserDept ud = UserDept.create().setId(id).oneById();
        if(null == ud){
            return Result.err("未获取到要删除的人员信息");
        }
        if(null != ud.getStatus() && ud.getStatus() != 1){
            return Result.err("该员工已被移除, 请刷新后重试");
        }
        ud.setStatus(0);
        ud.setUpdateId(getUserId());
        boolean b = ud.updateById();
        if(b) {
            return Result.ok();
        }
        return Result.err();
    }


    @Log("保存部门")
    @RequestMapping("/save")
    public Result save(@RequestBody SysDept dept){
        Long userId = getUserId();
        if(null == dept.getId()){
            dept.setCreateId(userId);
        }
        dept.setUpdateId(userId);
        //设置默认值
        dept.setStatus(1);
        int i = deptMapper.insertOrUpdate(dept);
        if(i>0){
            return  Result.ok();
        }
        return Result.err();
    }


    @Log("刪除部门")
    @RequestMapping("/remove")
    public Result delete(Long id){
        if(null == id){
            return Result.err("未获取到要删除的部门");
        }
        List<UserDept> list = UserDept.create().where(UserDept::getDeptId).eq(id).and(UserDept::getStatus).eq(1).list();
        if(list.size()>0){
            return Result.err("当前部门下关联有员工信息，请先移除该部门下的员工");
        }
        boolean flag = SysDept.create()
                .setId(id)
                .setStatus(0)
                .setUpdateId(getUserId())
                .updateById();
        if(flag){
            return Result.ok();
        }
        return Result.err();
    }

    @Log("刪除部门")
    @RequestMapping("/bachRemove")
    public Result bachDelete(List<Long> ids){
        if(ids.size()<=0){
            return Result.err("未获取到要删除的部门");
        }
        List<UserDept> list = UserDept.create().where(UserDept::getDeptId).in(ids).and(UserDept::getStatus).eq(1).list();
        if(list.size()>0){
            return Result.err("部门下关联有员工信息，请先移除该部门下的员工");
        }
        int i = 0;
        for(UserDept ud : list){
            i += SysDept.create()
                    .setId(ud.getId())
                    .setStatus(0)
                    .setUpdateId(getUserId())
                    .updateById()?1:0;
        }
        if(i>0){
            return Result.ok();
        }
        return Result.err();
    }
}
